package testing;

import api.betfairAPI.BetfairAPICallTypes;
import org.junit.Test;
import api.APICallRateMonitor;
import utils.ConsoleDisplay;
import utils.Display;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import static java.lang.Thread.sleep;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * User: Darren
 * Date: 8/12/12
 * Time: 11:25 PM
 */
public class APICallRateMonitorTest {
    private static final int SECS_PER_MIN = 60;
    private static final int MILLIS_PER_SEC = 1000;
    private static final int N_THREADS = 1;
    private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(N_THREADS);
    Display display = new ConsoleDisplay();

    @Test
    public void loginDoesNotExceedLimit() {
        APICallRateMonitor apiCallRateMonitor = new APICallRateMonitor(scheduler);
        assertFalse(apiCallRateMonitor.callExceedsLimit(BetfairAPICallTypes.LOGIN));
    }

    @Test
    public void logoutDoesNotExceedLimit() {
        APICallRateMonitor apiCallRateMonitor = new APICallRateMonitor(scheduler);
        assertFalse(apiCallRateMonitor.callExceedsLimit(BetfairAPICallTypes.LOGOUT));
    }

    @Test
    public void periodicLoginExceedsLimit() throws InterruptedException {
        APICallRateMonitor apiCallRateMonitor = new APICallRateMonitor(scheduler);
        BetfairAPICallTypes callType = BetfairAPICallTypes.LOGIN;
        display.displayTotalAndCallPerSecond(apiCallRateMonitor, callType);

        for (int i = 0; i < SECS_PER_MIN; ++i) {
            sleep(MILLIS_PER_SEC);
            if (i >= callType.getLimit()) {
                display.displayTotalAndCallPerSecond(apiCallRateMonitor, callType);
                assertTrue(apiCallRateMonitor.callExceedsLimit(callType));
                break;
            }
            display.displayTotalAndCallPerSecond(apiCallRateMonitor, callType);
            assertFalse(apiCallRateMonitor.callExceedsLimit(callType));
        }
    }

    @Test
    public void periodicGetBetDoesNotExceedLimit() throws InterruptedException {
        APICallRateMonitor apiCallRateMonitor = new APICallRateMonitor(scheduler);
        BetfairAPICallTypes callType = BetfairAPICallTypes.GET_BET;
        display.displayTotalAndCallPerSecond(apiCallRateMonitor, callType);

        for (int i = 0; i < SECS_PER_MIN * 2; ++i) {
            sleep(MILLIS_PER_SEC);
            display.displayTotalAndCallPerSecond(apiCallRateMonitor, callType);
            assertFalse(apiCallRateMonitor.callExceedsLimit(callType));
        }
    }
}
